﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ColorApplication.FileManager
{
    public partial class Downloads : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string filePath = string.Empty;
            try
            {
                bool blnFileDownload = false;
                if (!string.IsNullOrEmpty(Session["strDwnPath"].ToString()))
                {
                    filePath = Session["strDwnPath"].ToString();
                    Session["strDwnPath"] = "";
                }
                else
                {
                    throw new Exception("No filename");
                }
                if (filePath == "") return;
                Response.Clear();
                // Clear the content of the response
                Response.ClearContent();
                Response.ClearHeaders();
                // Buffer response so that page is sent
                // after processing is complete.
                Response.BufferOutput = true;
                // Add the file name and attachment,
                // which will force the open/cance/save dialog to show, to the header
                string fileName = filePath;
                if (filePath.ToLower().Contains("/preview/"))
                {
                    fileName = filePath.Substring(filePath.LastIndexOf('/') + 1);
                    blnFileDownload = true;
                }
                else
                {
                    blnFileDownload = false;
                }

                if (blnFileDownload == true && (File.Exists(Request.PhysicalApplicationPath + filePath) || File.Exists(Server.MapPath(filePath))))
                {
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
                    Response.ContentType = "application/octet-stream";
                    Response.WriteFile(filePath);
                    Response.End();
                    HttpContext.Current.ApplicationInstance.CompleteRequest();
                }
                else
                {
                    if (Request.UrlReferrer != null)
                    {
                        Type csType = GetType();
                        string jsScript = "alert('File Not Found');";
                        ScriptManager.RegisterClientScriptBlock(Page, csType, "popup", jsScript, true);
                    }
                }
            }
            catch (Exception ex)
            {
                string errorMsg = ex.Message;
            }
        }
    }
}